package com.market.plus.controller.validator;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.market.plus.core.dto.ParticipantDto;
import com.market.plus.core.service.ParticipantService;

@Component("participantValidator")
public class ParticipantValidator implements Validator {

   private ParticipantService participantService;

   public boolean supports(Class<?> classDef) {
      return ParticipantDto.class.isAssignableFrom(classDef);
   }

   public void validate(Object object, Errors errors) {
      validateClassDef(object, errors);
   }

   public void validateClassDef(Object object, Errors errors) {
      ParticipantDto participantDto = (ParticipantDto) object;
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "participant.firstName", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "participant.lastName", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "participant.userInfo.username", "err.required");
      ValidationUtils.rejectIfEmptyOrWhitespace(errors, "participant.userInfo.password", "err.required");
      if (!errors.hasFieldErrors("participant.firstName")) {
         if (StringUtils.containsWhitespace(participantDto.getFirstName())) {
            errors.rejectValue("participant.firstName", "err.containsWhitespace");
         }
      }
      
      if (!errors.hasFieldErrors("participant.userInfo.username")) {
         if (StringUtils.containsWhitespace(participantDto.getUserInfo().getUsername())) {
            errors.rejectValue("participant.userInfo.username", "err.containsWhitespace");
         }
      }

      if (!errors.hasFieldErrors("participant.userInfo.username")) {
         if (this.participantService.hasUserNameExist(participantDto.getUserInfo().getUsername())) {
            errors.rejectValue("participant.userInfo.username", "err.unique");
         }
      }
   }

   public void setParticipantService(ParticipantService participantService) {
      this.participantService = participantService;
   }

   public ParticipantService getParticipantService() {
      return participantService;
   }
}
